<template>
  <main-header :show-search="false" />
  <div class="product-detail-page">
    <!-- Breadcrumb Navigation -->
    <el-breadcrumb separator-icon="ArrowRight" class="breadcrumb-nav">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item v-if="categoryName">{{ categoryName }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ product?.name || '商品详情' }}</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="product-detail-container" v-if="product">
      <el-card shadow="never" class="product-card">
        <el-row :gutter="40" class="content-row">
          <!-- Left: Image Gallery -->
          <el-col :sm="24" :md="12">
            <div class="image-gallery">
              <el-image :src="currentImage" class="main-product-image" fit="contain" />
              <div class="thumbnail-strip">
                <el-image
                  v-for="(img, index) in galleryImages"
                  :key="index"
                  :src="img"
                  class="thumbnail-image"
                  :class="{ active: img === currentImage }"
                  @click="currentImage = img"
                  fit="cover"
                />
              </div>
            </div>
          </el-col>
          <!-- Right: Product Information -->
          <el-col :sm="24" :md="12">
            <div class="product-info">
              <div class="info-main">
                <h1>{{ product.name }}</h1>
                <div class="meta-info">
                  <el-tag type="success" v-if="product.quantity > 0">有货</el-tag>
                  <el-tag type="danger" v-else>暂时缺货</el-tag>
                  <span class="category-name">分类: {{ categoryName }}</span>
                </div>
                <p class="short-description">这里是一段吸引人的商品简介或标语，突出商品的核心卖点。</p>
                <div class="price-box">
                  <span class="price-label">价格:</span>
                  <span class="price-value">¥{{ product.price.toFixed(2) }}</span>
                </div>
              </div>
              
              <div class="actions">
                <el-form-item label="数量" class="quantity-selector">
                  <el-input-number v-model="quantity" :min="1" :max="product.quantity" size="large" />
                </el-form-item>
                <div class="button-group">
                  <el-button class="custom-btn primary" size="large" :disabled="product.quantity === 0" @click="handleBuyNow">立即购买</el-button>
                  <el-button class="custom-btn warning" size="large" :disabled="product.quantity === 0" @click="handleAddToCart">加入购物车</el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- Tabs for more details -->
        <el-tabs v-model="activeTab" class="detail-tabs">
          <el-tab-pane label="商品详情" name="description">
            <div class="tab-content" v-html="product.description"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="specs">
            <div class="tab-content specs-content">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="商品ID">{{ product.id }}</el-descriptions-item>
                    <el-descriptions-item label="分类">{{ categoryName }}</el-descriptions-item>
                    <el-descriptions-item label="库存">{{ product.quantity }} 件</el-descriptions-item>
                    <el-descriptions-item label="品牌">示例品牌</el-descriptions-item>
                </el-descriptions>
            </div>
          </el-tab-pane>
          <el-tab-pane label="用户评价" name="reviews">
             <div class="tab-content">
                <el-empty description="暂无评价" />
             </div>
          </el-tab-pane>
        </el-tabs>

      </el-card>
    </div>
    <div v-else-if="loading" v-loading="loading" class="loading-container" element-loading-text="正在加载商品..."></div>
    <div v-else class="not-found">
        <el-empty description="商品不存在或已下架" />
    </div>

    <!-- Order Confirmation Dialog -->
    <OrderConfirmationDialog
      v-if="product"
      v-model:visible="isDialogVisible"
      :product="product"
      :quantity="quantity"
      @order-success="handleOrderSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import apiClient from '../axios/axios';
import { ElMessage } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import OrderConfirmationDialog from '../components/OrderConfirmationDialog.vue';
import MainHeader from '../components/MainHeader.vue';
import { useCartStore } from '../stores/cart';

interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  categoryId: number;
  quantity: number;
  imageUrl: string;
}

interface Category {
  id: number;
  name: string;
  parentCategoryID: number | null;
  description: string;
}

const route = useRoute();
const router = useRouter();
const product = ref<Product | null>(null);
const quantity = ref(1);
const loading = ref(true);
const activeTab = ref('description');
const isDialogVisible = ref(false);

// Image gallery state
const galleryImages = ref<string[]>([]);
const currentImage = ref('');

// Category state
const categoryMap = ref<Map<number, string>>(new Map());
const categoryName = computed(() => {
    if (product.value) {
        return categoryMap.value.get(product.value.categoryId) || '未知分类';
    }
    return '';
});

const cartStore = useCartStore();

const handleAddToCart = () => {
  if (product.value) {
    cartStore.addItem(product.value.id, quantity.value);
  }
};

const handleBuyNow = () => {
    isDialogVisible.value = true;
};

const handleOrderSuccess = () => {
    // Optionally, redirect to an order confirmation page or refresh data
    console.log('Order placed successfully!');
    // Example: router.push('/my-orders');
};

const getCategories = async () => {
    try {
        const response = await apiClient.get<Category[]>('/category');
        response.data.forEach(c => categoryMap.value.set(c.id, c.name));
    } catch (error) {
        console.error('获取分类信息失败:', error);
    }
};

const setupGallery = (imageUrl: string) => {
    // Simulate a gallery with multiple images
    galleryImages.value = [
        imageUrl,
        'https://via.placeholder.com/800x800/eeeeee/333333?text=Detail+View+2',
        'https://via.placeholder.com/800x800/dddddd/333333?text=Detail+View+3',
        'https://via.placeholder.com/800x800/cccccc/333333?text=Detail+View+4',
    ];
    currentImage.value = galleryImages.value[0];
};

const getProductDetails = async () => {
  const productId = route.params.id;
  loading.value = true;
  try {
    const response = await apiClient.get<Product>(`/product/${productId}`);
    product.value = response.data;
    if (response.data) {
        setupGallery(response.data.imageUrl);
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    product.value = null;
    ElMessage.error('无法加载商品详情。');
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await getCategories();
  await getProductDetails();
});
</script>

<style scoped>
.product-detail-page {
  padding: 20px;
  background-color: #f5f7fa;
}

.breadcrumb-nav {
  margin-bottom: 20px;
  font-size: 1rem;
}

.product-card {
  border: none;
}

.content-row {
  display: flex;
  align-items: stretch; /* Ensure columns stretch to the same height */
}

/* Image Gallery */
.image-gallery {
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* To push thumbnails to the bottom */
  height: 100%;
}
.main-product-image {
  width: 100%;
  height: 380px; /* A more constrained height */
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  margin-bottom: 10px;
}
.thumbnail-strip {
  display: flex;
  gap: 10px;
}
.thumbnail-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}
.thumbnail-image:hover, .thumbnail-image.active {
  border-color: #f39c12; /* A shade of orange/yellow */
}

/* Product Info */
.product-info {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.info-main {
  flex-grow: 1; /* This will push the actions block to the bottom */
}
.product-info h1 {
  font-size: 2.2rem;
  font-weight: 600;
  margin-bottom: 1rem;
  line-height: 1.2;
}
.meta-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 1rem;
  color: #909399;
}
.short-description {
  color: #606266;
  font-size: 1rem;
  margin-bottom: 1.5rem;
}
.price-box {
  background-color: #fff9f2;
  padding: 15px 20px;
  border-radius: 8px;
  margin: 1.5rem 0;
}
.price-label {
  color: #909399;
  font-size: 1rem;
  margin-right: 10px;
}
.price-value {
  font-size: 2.5rem;
  color: #F56C6C;
  font-weight: bold;
}
.actions {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}
.actions .quantity-selector {
  margin-bottom: 1.5rem;
}
.actions .button-group {
  display: flex;
  gap: 15px;
}
.button-group .el-button.custom-btn {
  flex-grow: 1;
  border: none;
  color: white;
  transition: background-color 0.3s;
}

.custom-btn.primary {
  background-color: #e67e22; /* A nice orange */
}
.custom-btn.primary:hover, .custom-btn.primary:focus, .custom-btn.primary:active {
  background-color: #d35400; /* Darker orange */
}

.custom-btn.warning {
  background-color: #f39c12; /* A nice yellow/orange */
}
.custom-btn.warning:hover, .custom-btn.warning:focus, .custom-btn.warning:active {
  background-color: #e67e22; /* Darker yellow/orange */
}

/* Detail Tabs */
.detail-tabs {
  margin-top: 40px;
}
.tab-content {
  padding: 20px;
  min-height: 200px;
  line-height: 1.8;
  color: #303133;
}
.specs-content {
    padding: 20px 0;
}

.loading-container, .not-found {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
}
</style> 